package crew.blt.handsound.client.mvc.controller;

import crew.blt.handsound.client.Framework;
import crew.blt.handsound.client.mvc.model.Model;
import crew.blt.handsound.client.mvc.view.IMainView;
import crew.blt.handsound.client.mvc.view.MainView;
import crew.blt.handsound.client.mvc.view.SitePage;
import crew.blt.handsound.shared.domain.AuthType;
import crew.blt.handsound.shared.domain.User;

public class MainController implements IMainController<Model,IMainView>{
	
	private static final IMainController instance = new MainController();
	public static IMainController getInstance(){
		return instance;
	}

	private final Model model;
	private final IMainView<Model,IMainController> view;
	
	private MainController() {
		model = new Model();
		view = new MainView<Model, IMainController>(model,this);
	}
	
	private void logout(){
		Framework.get().redirectNativeByReplace("/logout");
	}
	
	private void setHomePage(){
		if(AuthType.authorizeUserPage(model.getUser(), SitePage.HOME)){
			Framework.get().setLocation(SitePage.HOME.location);
			view.setHomePage(model);
		}
	}
	
	private void setEditUserPage() {
		if(AuthType.authorizeUserPage(model.getUser(), SitePage.EDIT_USER)){
			Framework.get().setLocation(SitePage.EDIT_USER.location);
			view.setEditUserPage(model);
		}
	}
	
	private void setListUserPage() {
		if(AuthType.authorizeUserPage(model.getUser(), SitePage.USER)){
			Framework.get().setLocation(SitePage.USER.location);
			view.setListUserPage(model);
		}
	}
	
	@Override
	public void onUserChange(final User u) {
		model.setUser(u);
		view.onUserChange();
	}
	
	@Override
	public void onUserChange() {
	}


	public void onPageRequest(final SitePage page) {
		switch(page){
			case HOME:
				setHomePage();break;
			case EDIT_USER:
				setEditUserPage();break;
			case USER:
				setListUserPage();break;
			case LOGOUT:
				logout();break;
			default:
				setHomePage();break;
		}
	}

}
